package com.botu.sentineldemo1.demo;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: hanzeyao
 * @Date: 2019/12/5 16:32
 * @Description:
 */
public class Demo1 {
    /**
     * 限流规则
     */
    private static void initFlowRules(){
        List<FlowRule> rules = new ArrayList<>();
        FlowRule rule = new FlowRule();
        rule.setResource("HelloWorld");
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        rule.setCount(10);
        rules.add(rule);
        FlowRuleManager.loadRules(rules);
    }


    public static void main(String[] args) {
        initFlowRules();
        Entry entry =null;

        while(true){
            try{
                entry =SphU.entry("HelloWorld");
                System.out.println("hello");
            }catch(BlockException e){
                System.out.println("限流了");
            }finally {
                if(entry!=null){
                    entry.exit();
                }
            }
        }
            /*try (Entry entry = SphU.entry("HelloWorld")) {
                // 定义资源
                System.out.println("hello world");
            } catch (BlockException ex) {
                // 处理被流控的逻辑
                System.out.println("blocked!");
            }*/

    }




}
